﻿// $Id: TableIdentifierTypeConverter.cs 64 2008-05-06 18:29:47Z nvivo $

using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace DBLGen.UI.Design
{
    public class TableIdentifierTypeConverter : StringConverter
    {
        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            Table t = (Table) context.Instance;
            string propertyName = context.PropertyDescriptor.Name;

            // validate empty table name

            if (propertyName == "Name" && String.IsNullOrEmpty((string) value))
                throw new Exception("Value cannot be empty for table name.");

            // validate tables with the same name

            string schema = null;
            string table = null;

            switch (propertyName)
            {
                case "Name":
                    schema = t.Schema;
                    table = (string) value;
                    break;
                case "Schema":
                    schema = (string) value;
                    table = t.Name;
                    break;
            }

            if (t.Project != null && t.Project.Tables.Find(schema, table) != null)
                throw new Exception("There is a table with this name in the project already.");

            // if it reaches this point, everything is ok

            return base.ConvertFrom(context, culture, value);
        }
    }
}
